﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
namespace HPortal.Lib
{
    public class ImageHelper
    {
        # region cgImage Code
        public class cgImage
        {
            # region Value Code

            protected int ImageID_ = 0;
            protected string Type_ = string.Empty;
            protected byte[] Content_ = null;
            //		protected int Width_ = 0;
            //		protected int Height_ = 0;
            //		
            # endregion

            # region Methord Code

            public int ImageID
            {
                get { return ImageID_; }
                set { ImageID_ = value; }
            }

            //		public int Width
            //		{
            //			get{return Width_;}
            //			set{Width_ = value;}
            //		}
            //		public int Height
            //		{
            //			get{return Height_;}
            //			set{Height_ = value;}
            //		}

            public string Type
            {
                get { return Type_; }
                set { Type_ = value; }
            }

            public byte[] Content
            {
                get { return Content_; }
                set { Content_ = value; }
            }

            public cgImage()
            {
            }

            public DataTable SelectOne()
            {
                return DatabaseHelper.Select(new string[] { "Type", "Content", "Created" }, "Image", "ImageID=" + ImageID_);
            }

            public DataTable SelectAll()
            {
                return DatabaseHelper.Select(new string[] { "Type", "Content", "Created" }, "Image");
            }

            public int Insert()
            {
                int i = DatabaseHelper.Insert("Type", "Content", Content_, Type_, new string[] { "Created"/*,"Width","Height"*/}, new string[] { DatabaseHelper.GetDate/*,Width_.ToString(),Height_.ToString()*/}, "Image");
                // retrieve the new id

                ImageID_ = DatabaseHelper.SelectScalarInt("max(ImageID)", "Image", "([type]=" + DatabaseHelper.EscapeQuote(Type_) + ") AND (DAY([Created]) = DAY({ fn NOW() })) AND (MONTH([Created]) = MONTH({ fn NOW() }))");
                if (ImageID_ == 0)
                    throw new Exception(" - Error ImageHelper..!");
                return i;
            }

            public int Update()
            {
                if (Content_ != null && Content_.Length > 0)
                    return DatabaseHelper.Update("Type", "Content", Content_, Type_, new string[] { "Created"/*,"Width","Height"*/}, new string[] { DatabaseHelper.GetDate/*,Width_.ToString(),Height_.ToString()*/}, "Image", "ImageID=" + ImageID_);
                return DatabaseHelper.Update(new string[] { "Created"/*,"Width","Height"*/}, new string[] { DatabaseHelper.GetDate/*,Width_.ToString(),Height_.ToString()*/}, "Image", "ImageID=" + ImageID_);
            }

            public int Delete()
            {
                return DatabaseHelper.Delete("Image", "ImageID=" + ImageID_);
            }

            # endregion

            # region View,InsertImage Code

            public static void ViewImage(string ImageID, string ThumbnailID)
            {
                System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
                ViewImage(response, ImageID, ThumbnailID);
            }

            public static void ViewImage(System.Web.HttpResponse PageResponse, string ImageID, string ThumbnailID)
            {
                if (ImageID != null && ImageID != string.Empty)
                    ViewImage(PageResponse, "Type", "Content", "Image", "ImageID=" + ImageID);
            }

            public static void ViewImage(System.Web.HttpResponse PageResponse, string ImageType, string ImageContent, string Table, string Criterias)
            {
                try
                {
                    SqlDataReader reader = DatabaseHelper.SelectReader(new string[] { ImageType, ImageContent }, Table, Criterias);
                    if (reader.Read())
                    {
                        PageResponse.ContentType = (string)reader[ImageType];
                        PageResponse.BinaryWrite((byte[])reader[ImageContent]);
                    }
                    reader.Close();
                }
                catch { }
            }

            public static void ViewImage(string ImageType, string ImageContent, string Table, string Criterias)
            {
                System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
                ViewImage(response, ImageType, ImageContent, Table, Criterias);
            }

            public static int InsertImage_ReturnImageID(System.Web.UI.HtmlControls.HtmlInputFile HtmlFullImage)
            {
                try
                {
                    cgImage img = new cgImage();
                    img.Type = HtmlFullImage.PostedFile.ContentType;
                    byte[] content = new byte[HtmlFullImage.PostedFile.ContentLength];
                    HtmlFullImage.PostedFile.InputStream.Read(content, 0, content.Length);
                    img.Content = content;
                    img.Insert();
                    return img.ImageID;
                }
                catch (Exception ex)
                {
                    throw new Exception(" - Error ImageHelper! - " + ex.Message);
                }
            }
            # endregion

            # region ImgCounter Code
            private static double Fix(double Number)
            {
                if (Number >= 0)
                {
                    return Math.Floor(Number);
                }
                return -Math.Floor(-Number);
            }
            public static void WriteImgCounter(System.Web.UI.Page thisPage, string imgSrc, double hitcount)
            {
                WriteImgCounter(thisPage, imgSrc, hitcount, 9);
            }
            public static void WriteImgCounter(System.Web.UI.Page thisPage, string imgSrc, double hitcount, int digits)
            {
                System.Drawing.Image imgCounter = System.Drawing.Image.FromFile(imgSrc);
                int digit_width = (int)Math.Round((double)(((double)imgCounter.Width) / 10));
                int digit_height = imgCounter.Height;
                Bitmap bmpCounter = new Bitmap(digit_width * digits, digit_height, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
                Graphics grCounter = Graphics.FromImage(bmpCounter);
                int digits__ = digits - 1;
                for (int i = 0; i <= digits__; i++)
                {
                    int inti = (int)Math.Round((double)(Fix((double)(hitcount / Math.Pow(10, (double)((digits - i) - 1)))) - (Fix((double)(hitcount / Math.Pow(10, (double)(digits - i)))) * 10)));
                    Rectangle rtCounter2 = new Rectangle(i * digit_width, 0, digit_width, digit_height);
                    Rectangle rtCounter1 = new Rectangle(inti * digit_width, 0, digit_width, digit_height);
                    grCounter.DrawImage(imgCounter, rtCounter2, rtCounter1, GraphicsUnit.Pixel);
                }
                thisPage.Response.ContentType = "image/jpeg";
                bmpCounter.Save(thisPage.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
                grCounter.Dispose();
                bmpCounter.Dispose();
            }
            # endregion
        }
        #endregion
        public static byte[] GetThumbnail(System.Drawing.Image Img, Int64 quality, int width, int height)
        {
            int imgW = Img.Width;
            int imgH = Img.Height;
            if (width <= 0)
                width = imgW;
            if (height <= 0)
                height = imgH;
            ImageCodecInfo[] Info = ImageCodecInfo.GetImageEncoders();
            EncoderParameters Params = new EncoderParameters(1);
            Params.Param[0] = new EncoderParameter(Encoder.Quality, quality);
            using (MemoryStream ms = new MemoryStream())
            {
                using (Bitmap bmp = new Bitmap(width, height, PixelFormat.Format24bppRgb))
                {
                    using (Graphics grp = Graphics.FromImage(bmp))
                    {
                        grp.SmoothingMode = SmoothingMode.HighQuality;
                        grp.InterpolationMode = InterpolationMode.HighQualityBicubic;
                        grp.PixelOffsetMode = PixelOffsetMode.HighQuality;
                        grp.CompositingQuality = CompositingQuality.HighQuality;
                        grp.Clear(Color.White);
                        if (imgW > imgH)
                        {
                            int newH = width * imgH / imgW;
                            grp.DrawImage(Img, 0, (height - newH) / 2, width, newH);
                        }
                        else
                        {
                            int newW = height * imgW / imgH;
                            grp.DrawImage(Img, (width - newW) / 2, 0, newW, height);
                        }
                    }
                    bmp.Save(ms, Info[1], Params);
                }
                return ms.ToArray();
            }
        }
    }
}